package main

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwtSecret = []byte("AllYourBase")

type Claims struct {
	Username string `json:"username"`
	// 感谢 @剑尘 同学的提醒，这里修改为用户唯一码
	UserCode string `json:"user_code"`
	jwt.StandardClaims
}

func GenerateToken(username, user_code string) (string, error) {
	expireAt := time.Now().Add(time.Hour).Unix()

	claims := Claims{
		username,
		user_code,
		jwt.StandardClaims{
			ExpiresAt: expireAt,
			Issuer:    "xxxxxx",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}

func main() {
	token, err := GenerateToken("zhaobangyu", "10000")
	if err != nil {
		fmt.Println("GenerateToken is fail(err:%v)", err)
		return
	}
	fmt.Println("token=%s", token)

	//解析token
	claims, err := ParseToken(token)
	if err != nil {
		fmt.Println("ParseToken is fail(err:%v)", err)
		return
	}
	fmt.Println("Username=%s UserCode=%s", claims.Username, claims.UserCode)
}
